﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Threading.Tasks;

namespace OlapProject
{
    class ParseManager
    {
        private List<IParser> parsers = new List<IParser>();
        private Dictionary<int, IParser> prototypes;

        public ParseManager()
        {
            prototypes = new Dictionary<int, IParser>()   
            {
                 {0,new FreeAgentHouseParser()},
                 {1,new HomeOneSaleParser()},
                 {2,new ImlixParser()},
                 {3,new PropertyAndMoreParser()},              
                 {4,new Prian()}                
            };
        }

        public void run()
        {
            if (parsers.Count == 0)
                return;          

            Parallel.ForEach(parsers, currentParser =>
            {
                List<PropertyVO> data = currentParser.getData();
                DatabaseHandler db = new DatabaseHandler();
                try
                {
                    db.connection.Open();
                    foreach (PropertyVO property in data)
                    {
                        db.insertRow(property);
                    }
                    clean(db);
                }
                catch (Exception ex)
                {
                    clean(db);
                    Log.writeLine(ex.Message, Color.Red);
                }

               
	      
            });
        }

        private static void clean(DatabaseHandler db)
        {
            RDB rdb = new RDB(db.connection, "temp");
            rdb.removeTrash();
            rdb.move();
            db.connection.Close();
        }

        public void useParser(int tag)
        {
            parsers.Add(prototypes[tag]);
        }

        public void reset()
        {
            parsers.Clear();
        }
    }
}
